<template>
  <div class="body-wrapper">
    <div class="header">
      <p>专注进出口贸易数据统计分析，一站式数据查询平台</p>
    </div>
    <div class="container">
      <el-row :gutter="20">
        <!-- 左侧导航 -->
        <el-col :span="4">
          <el-menu
            :default-active="activeMenu"
            class="side-menu"
            @select="handleMenuSelect"
            
          >
            <div class="active-img">
              <div class="user-profile">
                <el-avatar :size="80" :src="userData.headerPic" />
                <div class="user-info">
                  <h4>{{ userData.userName }}</h4>
                </div>
              </div>
            </div>
            <el-menu-item
              v-for="item in menuItems"
              :key="item.id"
              :index="item.id"
            >
              <el-icon>
                <component :is="item.icon" />
              </el-icon>
              <span>{{ item.label }}</span>
            </el-menu-item>

            <el-menu-item index="logout">
              <el-icon><SwitchButton /></el-icon>
              <span>退出登录</span>
            </el-menu-item>
          </el-menu>
        </el-col>

        <!-- 右侧内容 -->
        <el-col :span="20">
          <div class="content-area">
            <!-- 个人信息 -->
            <UserFrom
              v-show="activeMenu === 'info'"
              :user-data="userData"
              @update-user="updateUserData"
            ></UserFrom>

            <!-- 用户认证 -->
            <Authentication v-show="activeMenu === 'auth'"></Authentication>

            <!-- 我的订单 -->
            <Order v-show="activeMenu === 'orders'"></Order>

            <!-- 我的钱包 -->
            <Wallet
              v-show="activeMenu === 'wallet'"
              :wallets="walletData"
              :balances="balance"
              :loading="isLoading"
              @myAccDetail="myAccDetail"
              :total="pagination.total"
              :initial-page="pagination.pageNum"
              :initial-size="pagination.pageSize"
            ></Wallet>

            <!-- 我的笔记 -->
            <Notes
              v-show="activeMenu === 'notes'"
              :noteData="noteDatas"
              :loading="isLoading"
              :total="pagination.total"
              :initial-page="pagination.pageNum"
              :initial-size="pagination.pageSize"
              @refresh="handleNotes"
            ></Notes>
            <!-- 我的上传 -->
            <Upload
              v-show="activeMenu === 'upload'"
              :uploadsdata="userUploads"
              :loading="isLoading"
              :total="pagination.total"
              :initial-page="pagination.pageNum"
              :initial-size="pagination.pageSize"
              @refresh="loadUploadsData"
            />

            <!-- 我的下载 -->
            <Downloads
              v-show="activeMenu === 'download'"
              :downloadsdata="downloads"
              :loading="isLoading"
              :total="pagination.total"
              :initial-page="pagination.pageNum"
              :initial-size="pagination.pageSize"
              @refresh="handleDownload"
            ></Downloads>

            <!-- 我的收藏 -->
            <Favorites
              v-show="activeMenu === 'favorites'"
              :favoritesDatas="favoritesData"
              :loading="isLoading"
              :total="pagination.total"
              :initial-page="pagination.pageNum"
              :initial-size="pagination.pageSize"
              @refresh="handleFavorites"
            ></Favorites>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
  
  <script setup>
import { ref, reactive } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'

import UserFrom from './components/User.vue'
import Authentication from './components/Authentication.vue'
import Order from './components/order.vue'
import Wallet from './components/wallet.vue'
import Notes from './components/notes.vue'
import Upload from './components/upload.vue'
import Downloads from './components/download.vue'
import Favorites from './components/favorites.vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/index.js'
import { upload } from '../api/upload'
import { download } from '../api/Download'
import { favorites } from '../api/favorites'
import { notes } from '../api/notes'
import { order } from '../api/order'
import { wallet } from '../api/wallet'

// 上传
const userUploads = ref([])
// 下载
const downloads = ref([])
// 收藏
const favoritesData = ref([])
// 笔记
const noteDatas = ref([])
// 钱包
const walletData = ref([])
// 余额
const balance = ref({})
const isLoading = ref(false)
const authStore = useAuthStore()
const router = useRouter()

import {
  User,
  Stamp,
  Tickets,
  Setting,
  CreditCard,
  EditPen,
  UploadFilled,
  Download,
  StarFilled

} from '@element-plus/icons-vue'

const userData = ref({

  userName: authStore.userInfo.userName || '未设置',
  headerPic: authStore.userInfo.headerPic
})

// 接收用户信息更新的方法
const updateUserData = (newData) => {
  console.log(newData)
  userData.value = newData
}


// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => {
      authStore.logout()
      router.push('/login')
    })
    .catch(() => {
      // 用户取消，无需处理
    })
}


const menuItems = ref([
  {
    id: 'info',
    icon: User,
    label: '个人信息'
  },
  {
    id: 'auth',
    icon: Stamp,
    label: '用户认证'
  },
  {
    id: 'orders',
    icon: Tickets,
    label: '我的订单'
  },
  {
    id: 'wallet',
    icon: CreditCard,
    label: '我的钱包'
  },
  {
    id: 'notes',
    icon: EditPen,
    label: '我的笔记'
  },
  {
    id: 'upload',
    icon: UploadFilled,
    label: '我的上传'
  },
  {
    id: 'download',
    icon: Download,
    label: '我的下载'
  },
  {
    id: 'favorites',
    icon: StarFilled,
    label: '我的收藏'
  },

])
const activeMenu = ref(menuItems.value[0].id)



// 用 reactive 管理分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})


// 菜单选择处理
const handleMenuSelect = async (index) => {
  if (index === 'logout') {
    handleLogout()
    return
  }
  activeMenu.value = index

  // 当切换到上传菜单时加载数据
  if (index === 'upload') {
    await loadUploadsData()
  }
  if (index === 'download') {
    await handleDownload()
  }
  if (index === 'favorites') {
    await handleFavorites()
  }
  if (index === 'notes') {
    await handleNotes()
  }
  if (index === 'orders') {

  }
  if (index === 'wallet') {
    await handleWallet()
    await myAccDetail()

  }

}
// 我的上传-数据加载
const loadUploadsData = async ({ pageNum = pagination.pageNum, pageSize = pagination.pageSize } = {}) => {
  try {
    isLoading.value = true
    const res = await upload.myReportList({ pageNum, pageSize })
    if (res.code === 0) {
      userUploads.value = res.data.myReportList?.info || []
      pagination.total = res.data.myReportList.num || 0
      pagination.pageNum = pageNum
      pagination.pageSize = pageSize
    }
    else {
      throw new Error(res.msg || '数据加载失败')
    }
  } catch (err) {
    ElMessage.error(err.message)
    userUploads.value = []
  } finally {

    setTimeout(() => isLoading.value = false, 500)
  }
}
// 我的下载
const handleDownload = async ({pageNum=pagination.pageNum,pageSize=pagination.pageSize}={}) => {
  try {
    isLoading.value = true
    const res = await download.myReporDowntList({pageNum,pageSize})
    if (res.code === 0) {
      downloads.value = res.data.myDownList?.info || [] // 正确赋值给downloads
      pagination.total=res.data.myDownList.num||0
      pagination.pageNum=pageNum
      pagination.pageSize=pageSize
    }
  } catch (err) {
    ElMessage.error(err.message)
    downloads.value = []
  } finally {
    setTimeout(() => isLoading.value = false, 500)
  }
}
// 我的收藏
const handleFavorites = async ({pageNum=pagination.pageNum,pageSize=pagination.pageSize}={}) => {
  try {
    isLoading.value = true
    const res = await favorites.favoritesReportList({pageNum,pageSize})
    if (res.code === 0) {
      favoritesData.value = res.data.myCollectList?.info || []
      pagination.total=res.data.myCollectList.num||0
      pagination.pageNum=pageNum
      pagination.pageSize=pageSize
    }
  } catch (err) {
    ElMessage.error(err.message)
    favoritesData.value = []
  } finally {
    setTimeout(() => isLoading.value = false, 500)
  }
}
// 我的笔记
const handleNotes = async({pageNum=pagination.pageNum,pageSize=pagination.pageSize}={}) => {
  try {
    isLoading.value = true
    const res = await notes.SearchNotes({pageNum,pageSize})
    if (res.code === 0) {
      noteDatas.value = res.data.myNoteReportList?.info || []
      pagination.total=res.data.myNoteReportList.num||0
      pagination.pageNum=pageNum
      pagination.pageSize=pageSize
    }
  } catch (err) {
    ElMessage.error(err.message)
    noteDatas.value = []
  } finally {
    setTimeout(() => isLoading.value = false, 500)
  }
}
// 我的钱包
const handleWallet = async ({pageNum=pagination.pageNum,pageSize=pagination.pageSize}={}) => {
  try {
    isLoading.value = true
    const res = await wallet.getWalletList({pageNum,pageSize})
    if (res.code === 0) {
      walletData.value = res.data.myDividend?.info || []
      pagination.total=res.data.myDividend.num||0
      pagination.pageNum=pageNum
      pagination.pageSize=pageSize
    }
  } catch (err) {
    // ElMessage.error(err.message)
    walletData.value = []
  } finally {
    setTimeout(() => isLoading.value = false, 500)
  }
}
// 我的钱包
const myAccDetail = async () => {
  try {
    isLoading.value = true
    const res = await wallet.getWallet()
    if (res.code === 0) {
      balance.value = res.data.myAccDetail || {}
    }
  } catch (err) {
    ElMessage.error(err.message)
    balance.value = []
  } finally {
    setTimeout(() => isLoading.value = false, 500)
  }
}

  </script>
  
  <style lang="scss" scoped>
.body-wrapper {
  width: 100%;
  height: 100%;
   background: linear-gradient(
    to bottom,
    rgba(240, 250, 255, 0.7) 0%,
    rgba(255, 255, 255, 1) 100%
  );
  // background: url("../assets/xwimg/userBg.png") center/cover no-repeat;
}
.container {
  width: 85%;
  margin: 0px auto;
  padding: 20px 0;
  min-height: calc(80vh - 80px); // 减去顶栏高度
}
.header {
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("../assets/xwimg/dataQueryH.png") center/cover no-repeat;
  p {
    font-weight: 600;
    font-size: 30px;
    color: #004d7d;
    margin: 0;
    padding: 0 20px;
    letter-spacing: 5px;
  }
}

.el-row {
  height: 100%;
}

.side-menu {
  height: 730px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px 0;

  .el-menu-item {
    height: 44px;
    line-height: 44px;
    padding: 0 24px !important;
    margin: 4px 0;
    border-radius: 4px;
    color: #606266;
    font-size: 14px;
    transition: background 0.3s, color 0.3s;

    i {
      font-size: 18px;
      margin-right: 8px;
      vertical-align: middle;
    }

    &:hover {
      background: #e6f7ff;
      color: #409eff;
    }

    &.is-active {
      background: #e6f7ff;
      color: #409eff;
    }
  }
}

.active-img {
  padding: 20px;
  .user-profile {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 15px;
    .user-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      h4 {
        color: #151618e3;
        margin: 0;
        font-size: 18px;
      }
      p {
        color: #1516188f;
        font-size: 14px;
        opacity: 0.9;
      }
    }
  }
}
.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;

  .security-label {
    font-weight: 500;
    font-size: 16px;
    color: #333;
  }

  .el-button {
    margin-left: auto;
  }
}
/* 密码强度提示 */
.password-strength {
  font-size: 12px;
  color: #666;
  margin-top: 4px;

  &::before {
    content: "密码强度：";
  }

  &.weak {
    color: #e6a23c;
  }
  &.medium {
    color: #409eff;
  }
  &.strong {
    color: #67c23a;
  }
}

/* 弹窗底部按钮对齐 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
  